﻿using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Abp.Authorization;
using Abp.Runtime.Validation;

namespace pandx.Mulan.Authorization.Permissions
{
    public static class PermissionManagerExtension
    {
        public static IEnumerable<Permission> GetPermissionsFromNamesByValidating(
            this IPermissionManager permissionManager, IEnumerable<string> permissionNames)
        {
            var permissions = new List<Permission>();
            var undefinedPermissionNames = new List<string>();
            foreach (var permissionName in permissionNames)
            {
                var permission = permissionManager.GetPermissionOrNull(permissionName);
                if (permission == null)
                {
                    undefinedPermissionNames.Add(permissionName);
                }

                permissions.Add(permission);
            }

            if (undefinedPermissionNames.Count > 0)
            {
                throw new AbpValidationException($"存在 {undefinedPermissionNames.Count} 个未定义的权限")
                {
                    ValidationErrors = undefinedPermissionNames.Select(p => new ValidationResult($"未定义的权限：{p}"))
                        .ToList()
                };
            }

            return permissions;
        }
    }
}
